#import "RegisterDoneViewController.h"
#import "RegisterViewController.h"
#import "RegexKitLite.h"
#import "UserManager.h"
#import "NetWorkManager.h"

@interface RegisterDoneViewController ()

@end

@implementation RegisterDoneViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc {
    PP_RELEASE(hudLoading);
    PP_RELEASE(username);
    PP_RELEASE(registerUserImage);
    PP_RELEASE(registerDoneBtn);
    PP_RELEASE(registerDoneUsernameBg);
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.backgroundColor =[UIColor clearColor]; //导航上那条黑线的原因在这里
    baseTitle.text = @"注册";
    
    UIButton* backBtn= [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"nav_bar_back_1.png"] forState:UIControlStateNormal];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"nav_bar_back_2.png"] forState:UIControlStateHighlighted];
    [backBtn addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* backBarBtn= [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    [self.navigationItem setLeftBarButtonItem:backBarBtn];
    [backBarBtn release];
    [backBtn release];
    
    UIImage *registerDoneBgImage = [[UIImage imageNamed:@"register_username_bg.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:21];
    registerDoneUsernameBg.image = registerDoneBgImage;
    
    UIImage *registerBtnBgImageOne = [[UIImage imageNamed:@"login_btn_1.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:21];
    UIImage *registerBtnBgImageTwo = [[UIImage imageNamed:@"login_btn_2.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:21];

    [registerDoneBtn setBackgroundImage:registerBtnBgImageOne forState:UIControlStateNormal];
    [registerDoneBtn setBackgroundImage:registerBtnBgImageTwo forState:UIControlStateHighlighted];

    
    username = [[[UITextField alloc] initWithFrame:CGRectMake(registerUserImage.frame.origin.x +40, registerUserImage.frame.origin.y-8, 230, 40)] autorelease];
    username.userInteractionEnabled = YES;
    username.delegate = self;
    username.borderStyle = UITextBorderStyleNone;
    username.contentVerticalAlignment= UIControlContentVerticalAlignmentCenter;
    username.placeholder = @"用户名";
    [username addTarget:self
                   action:@selector(textFieldDoneEditing:)
         forControlEvents:UIControlEventEditingDidEndOnExit];
    [self.view addSubview:username];
}

- (void)viewDidUnload
{
    PP_RELEASE(hudLoading);
    PP_RELEASE(username);
    PP_RELEASE(registerUserImage);
    PP_RELEASE(registerDoneBtn);
    PP_RELEASE(registerDoneUsernameBg);
    [super viewDidUnload];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    [username becomeFirstResponder];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)doRegister
{
    [username resignFirstResponder];
    
    //用户名验证
    if (![username.text isMatchedByRegex:@"^\\S{2,}$"]) {
//        [self baseShowHUD:@"用户名不少于2位" atY:60.0];
        [self baseShowInfoHud:NSLocalizedString(@"用户名不少于2位", @"") andIsTop:YES];

        [username resignFirstResponder];
        return;
    }
    
    HAS_NO_NETWORK(self);
    
    hudLoading = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hudLoading.labelText = @"正在注册...";
    hudLoading.opacity = PP_mbprogressHudOpacity;
    [self.view.window addSubview:hudLoading];

    //GDC多线程的使用
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        UserManager *tUserManager = [UserManager sharedInstance];
        BOOL succ = [tUserManager registerWithEmail:tUserManager.email password:tUserManager.password username:username.text];
        dispatch_async(dispatch_get_main_queue(), ^{
            if(!succ){
                [hudLoading hide:YES];
                [self baseShowInfoHud:[UserManager sharedInstance].registerErrInfo andIsTop:NO];
            }else{
                hudLoading.labelText = @"注册成功,正在登录...";
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                //自动登录
                NSString *err = [tUserManager loginWithEmail:tUserManager.email password:tUserManager.password remember:@"on"];
                dispatch_async(dispatch_get_main_queue(), ^{
                        if ([UserManager sharedInstance].isLogin) {
                            [hudLoading hide:YES];
                            [self baseShowInfoHud:err andIsTop:NO];
                            [self back];
                        }else{
                            [hudLoading hide:YES];
                            [self baseShowInfoHud:err andIsTop:NO];
                            [self back];
                        }
                    });
                });
                
            }
        });
    });
}

- (void)back{
    if ([self respondsToSelector:@selector(presentingViewController)]) {
        
        if (self.presentedViewController) {
            [[self presentedViewController] dismissModalViewControllerAnimated:YES];
        }
        else {
            [self dismissModalViewControllerAnimated:YES];
        }
    }else {
        [[self parentViewController] dismissModalViewControllerAnimated:YES];
    }
}


-(void) back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag == 0){
    } else if(alertView.tag == 1){
        [self.navigationController popToViewController:[[self.navigationController viewControllers] objectAtIndex:0] animated:YES];
    }
}

@end
